//
//  TaskManagerDetailVC.m
//  LogisticsSupplier
//
//  Created by 吕晶 on 2021/3/22.
//  Copyright © 2021 吕晶. All rights reserved.
//

#import "TaskManagerDetailVC.h"
#import "TaskManagerDetailModel.h"
#import "TaskManagerDetailHeadView.h"
#import "TaskManagerDetailCell.h"
#import "MyTakeOrderDetailVC.h"
#import "MyTransportOrderDetailVC.h"
#import "ZhuangCheMainVC.h"
#import "BoHuiReasonAlertView.h"
#import "AbnormalReportMainVC.h"

@interface TaskManagerDetailVC () <UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) TaskManagerDetailModel *model;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) TaskManagerDetailHeadView *headView;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UILabel *goodTypeLab;
@property (nonatomic, strong) UILabel *allPnumLab;
@property (nonatomic, strong) UILabel *allNumLab;
@property (nonatomic, strong) UILabel *allWeightLab;
@property (nonatomic, strong) UILabel *allVolumeLab;

@end

@implementation TaskManagerDetailVC

-(UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenH - NaviHeight - BottomHeight - (15 + 17 + 10 + 17 + 10 + 17 + 5 + 17 + 15 + 44 + 10), ScreenW, BottomHeight + 15 + 17 + 10 + 17 + 10 + 17 + 5 + 17 + 15 + 44 + 10)];
        _bottomView.backgroundColor = HexColor(0xffffff);
        
        UIButton *sureBtn = [[UIButton alloc] initWithFrame:CGRectMake(30, _bottomView.nim_height - BottomHeight - 10 - 44, _bottomView.nim_width - 60, 44)];
        [sureBtn setBackgroundColor:HexColor(0x3D68EB)];
        sureBtn.layer.masksToBounds = YES;
        sureBtn.layer.cornerRadius = 6;
        [sureBtn setImage:[UIImage imageNamed:@"icon_adopt"] forState:0];
        [sureBtn setTitle:@"确认收货" forState:0];
        sureBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
        [sureBtn setTitleColor:HexColor(0xffffff) forState:0];
        sureBtn.titleLabel.font = BoldFontOfSize(16);
        [sureBtn addTarget:self action:@selector(shouHuoClick) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView addSubview:sureBtn];
        
        UILabel *title1 = [[UILabel alloc] initWithFrame:CGRectMake(30, 15, _bottomView.nim_width - 60, 17)];
        title1.font = BoldFontOfSize(16);
        title1.textColor = HexColor(0x9C9DB3);
        title1.text = @"包含类型";
        [_bottomView addSubview:title1];
        
        self.goodTypeLab = [[UILabel alloc] initWithFrame:CGRectMake(30, title1.nim_bottom + 10, _bottomView.nim_width - 30, 17)];
        self.goodTypeLab.font = BoldFontOfSize(16);
        self.goodTypeLab.textColor = HexColor(0x2B2C44);
        [_bottomView addSubview:self.goodTypeLab];
        
        UILabel *title2 = [[UILabel alloc] initWithFrame:CGRectMake(30, 10 + self.goodTypeLab.nim_bottom, [FactoryMethod sizeWithText:@"总件数：" font:[UIFont systemFontOfSize:16] maxSize:CGSizeMake(0, 0)].width, 17)];
        title2.font = [UIFont systemFontOfSize:16];
        title2.textColor = HexColor(0x9C9DB3);
        title2.text = @"总件数：";
        [_bottomView addSubview:title2];
        
        self.allPnumLab = [[UILabel alloc] initWithFrame:CGRectMake(title2.nim_right, title2.nim_top, _bottomView.nim_width * 0.5 - title2.nim_right, title2.nim_height)];
        self.allPnumLab.font = [UIFont systemFontOfSize:16];
        self.allPnumLab.textColor = HexColor(0x2B2C44);
        [_bottomView addSubview:self.allPnumLab];
        
        UILabel *title3 = [[UILabel alloc] initWithFrame:CGRectMake(_bottomView.nim_width * 0.5, 15 + self.goodTypeLab.nim_bottom, [FactoryMethod sizeWithText:@"总数量：" font:[UIFont systemFontOfSize:16] maxSize:CGSizeMake(0, 0)].width, 17)];
        title3.font = [UIFont systemFontOfSize:16];
        title3.textColor = HexColor(0x9C9DB3);
        title3.text = @"总数量：";
        [_bottomView addSubview:title3];
        
        self.allNumLab = [[UILabel alloc] initWithFrame:CGRectMake(title3.nim_right, title3.nim_top, _bottomView.nim_width - 30 - title3.nim_right, title3.nim_height)];
        self.allNumLab.font = [UIFont systemFontOfSize:16];
        self.allNumLab.textColor = HexColor(0x2B2C44);
        [_bottomView addSubview:self.allNumLab];
        
        UILabel *title4 = [[UILabel alloc] initWithFrame:CGRectMake(30, 5 + title2.nim_bottom, [FactoryMethod sizeWithText:@"总重量：" font:[UIFont systemFontOfSize:16] maxSize:CGSizeMake(0, 0)].width, 17)];
        title4.font = [UIFont systemFontOfSize:16];
        title4.textColor = HexColor(0x9C9DB3);
        title4.text = @"总重量：";
        [_bottomView addSubview:title4];
        
        self.allWeightLab = [[UILabel alloc] initWithFrame:CGRectMake(title4.nim_right, title4.nim_top, _bottomView.nim_width * 0.5 - title4.nim_right, title4.nim_height)];
        self.allWeightLab.font = [UIFont systemFontOfSize:16];
        self.allWeightLab.textColor = HexColor(0x2B2C44);
        [_bottomView addSubview:self.allWeightLab];
        
        UILabel *title5 = [[UILabel alloc] initWithFrame:CGRectMake(_bottomView.nim_width * 0.5, 5 + title2.nim_bottom, [FactoryMethod sizeWithText:@"总体积：" font:[UIFont systemFontOfSize:16] maxSize:CGSizeMake(0, 0)].width, 17)];
        title5.font = [UIFont systemFontOfSize:16];
        title5.textColor = HexColor(0x9C9DB3);
        title5.text = @"总体积：";
        [_bottomView addSubview:title5];
        
        self.allVolumeLab = [[UILabel alloc] initWithFrame:CGRectMake(title5.nim_right, title5.nim_top, _bottomView.nim_width - 30 - title5.nim_right, title5.nim_height)];
        self.allVolumeLab.font = [UIFont systemFontOfSize:16];
        self.allVolumeLab.textColor = HexColor(0x2B2C44);
        [_bottomView addSubview:self.allVolumeLab];
    }
    return _bottomView;
}

- (void)shouHuoClick {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"是否确认收货？" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self requestForShouHuo];
    }];
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

    }];
    [alert addAction:sureAction];
    [alert addAction:cancleAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)requestForShouHuo {
    [HttpRequest PostWithApi:LogisticsSupplierTaskShouHuo params:@{@"sta_id":self.sta_id} progress:^(NSProgress * _Nonnull progress) {
            
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            [MBProgressHUD leShowSuccessHUDAddedTo:self.view message:@"已收货"];
            [self requestForDetail];
            [[NSNotificationCenter defaultCenter] postNotificationName:ReceiptDeliveryRefreshTaskManagerList object:nil];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

-(TaskManagerDetailModel *)model {
    if (!_model) {
        _model = [TaskManagerDetailModel new];
    }
    return _model;
}

-(TaskManagerDetailHeadView *)headView {
    if (!_headView) {
        _headView = [[TaskManagerDetailHeadView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 135)];
    }
    return _headView;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH - NaviHeight - BottomHeight) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = Color_backgroundColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.tableHeaderView = self.headView;
        __weak_self;
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakself requestForDetail];
        }];
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"任务详情";
    [self.view addSubview:self.tableView];
    [self requestForDetail];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestForDetail) name:ReceiptDeliveryRefreshTaskManagerDetail object:nil];
}

- (void)requestForDetail {
    [HttpRequest PostWithApi:self.isBoHui ? LogisticsSupplierTaskManagerBoHuiDetail : LogisticsSupplierTaskManagerDetail params:@{@"sta_id":self.sta_id} progress:^(NSProgress * _Nonnull progress) {
            
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            self.model = [TaskManagerDetailModel mj_objectWithKeyValues:responseObject];
            [self.model.list enumerateObjectsUsingBlock:^(TaskManagerDetailOrderModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//                obj.is_dp_wa = self.model.is_dp_wa;
                obj.is_sta_type = self.model.is_sta_type;
//                obj.countdown = [TimeModel pleaseInsertStarTime:[TimeModel stringFromDate:[NSDate date] andFormatter:@"yyyy/MM/dd HH:mm:ss"] andInsertEndTime:[TimeModel dateFromLongLong:[obj.arrivalTime longLongValue] andFormatter:@"yyyy/MM/dd HH:mm:ss"]];
                
            }];
            [self configUI];
            self.headView.model = self.model;
            self.headView.nim_height = self.model.is_sta_type == 1 ?  135 : 107;
            [self.tableView reloadData];
        }
        [self.tableView.mj_header endRefreshing];
        [self stopTimer];
        [self startTimer];
    } fail:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
    }];
}

- (void)configUI {
    if ([self.model.status isEqualToString:@"2"]) {
        //多车 显示调度和收货
        if (self.model.is_stick != 1) {
            //第一棒 不显示收货 其余显示
            if (self.model.is_receie == 1) {
                //收货未完成
                [self.view addSubview:self.bottomView];
                self.tableView.frame = CGRectMake(0, 0, ScreenW, ScreenH - NaviHeight - self.bottomView.nim_height);
                NSMutableString *trans_type = [NSMutableString string];
                [self.model.list enumerateObjectsUsingBlock:^(TaskManagerDetailOrderModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if (obj.trans_type) {
                        if (![trans_type containsString:obj.trans_type]) {
                            [trans_type appendFormat:@"%@/",obj.trans_type];
                        }
                    }
                }];
                if (trans_type.length) {
                    [trans_type deleteCharactersInRange:NSMakeRange(trans_type.length - 1, 1)];
                }
                self.goodTypeLab.text = trans_type;
                self.allPnumLab.text = self.model.all_pnum;
                self.allNumLab.text = self.model.all_num;
                self.allWeightLab.text = [NSString stringWithFormat:@"%@KG",self.model.all_weight];
                self.allVolumeLab.text = [NSString stringWithFormat:@"%@m³",self.model.all_volume];
            }else {
                [self.bottomView removeFromSuperview];
                self.tableView.frame = CGRectMake(0, 0, ScreenW, ScreenH - NaviHeight   - BottomHeight);
            }
        }else {
            [self.bottomView removeFromSuperview];
            self.tableView.frame = CGRectMake(0, 0, ScreenW, ScreenH - NaviHeight   - BottomHeight);
        }
        if (self.model.is_plan == 2) {
            [self.bottomView removeFromSuperview];
            self.tableView.frame = CGRectMake(0, 0, ScreenW, ScreenH - NaviHeight - BottomHeight);
        }
    }else {
        [self.bottomView removeFromSuperview];
        self.tableView.frame = CGRectMake(0, 0, ScreenW, ScreenH - NaviHeight - BottomHeight);
    }
}

//开启定时器
-(void)startTimer {
     if (!self.timer) {
          self.timer = [NSTimer scheduledTimerWithTimeInterval:1
                                                        target:self
                                                      selector:@selector(timerLoop)
                                                      userInfo:nil
                                                       repeats:YES];
          [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
     }
}

//停止定时器
-(void)stopTimer {
     if (self.timer) {
          [self.timer invalidate];
          self.timer = nil;
     }
}
//计时
-(void)timerLoop {
    [self.model.list enumerateObjectsUsingBlock:^(TaskManagerDetailOrderModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.countdown > 0) {
            obj.countdown -= 1;
            TaskManagerDetailCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:idx inSection:0]];
            [cell configWithTime:obj.countdown];
        }
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.model.list.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TaskManagerDetailCell *cell = [TaskManagerDetailCell TaskManagerDetailCellWithTableView:tableView];
    TaskManagerDetailOrderModel *model = self.model.list[indexPath.row];
    cell.model = model;
    __weak_self;
    cell.detailBlock = ^{
        if (model.is_dp_wa == 1) {
            MyTakeOrderDetailVC *vc = [MyTakeOrderDetailVC new];
            vc.dp_id = [model.dp_id intValue];
            [weakself.rt_navigationController pushViewController:vc animated:YES];
        }else if (model.is_dp_wa == 2) {
            MyTransportOrderDetailVC *vc = [MyTransportOrderDetailVC new];
            vc.wa_id = [model.dp_id intValue];
            vc.isMyReceive = NO;
            [weakself.rt_navigationController pushViewController:vc animated:YES];
        }
    };
    cell.sureDaoDaBlock = ^{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"是否确认到达？" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [weakself requestForDaoDaWithTaskID:weakself.model.Id withDP_ID:model.dp_id withD_Status:model.d_status];
        }];
        UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

        }];
        [alert addAction:sureAction];
        [alert addAction:cancleAction];
        [weakself presentViewController:alert animated:YES completion:nil];
    };
    cell.dianHuoZhuangCheBlock = ^{
        ZhuangCheMainVC *vc = [ZhuangCheMainVC new];
        vc.sta_id = weakself.model.Id;
        vc.dp_id = model.dp_id;
        [weakself.rt_navigationController pushViewController:vc animated:YES];
    };
    cell.yiJianZhuangCheBlock = ^{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"确认一键装车？" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [weakself requestForYiJianZhuangChe:model.dp_id];
        }];
        UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:sureAction];
        [alert addAction:cancleAction];
        [weakself presentViewController:alert animated:YES completion:nil];
    };
    cell.yiChangShangBaoBlock = ^{
        AbnormalReportMainVC *vc = [AbnormalReportMainVC new];
        vc.isPush = YES;
        vc.sta_id = weakself.model.Id;
        vc.dp_id = model.dp_id;
        vc.type = 2;
        [weakself.rt_navigationController pushViewController:vc animated:YES];
    };
    cell.boHuiReasonBlock = ^{
        BoHuiReasonAlertView *alert = [BoHuiReasonAlertView new];
        alert.timeStr = model.reject_remarks;
        alert.reasonStr = model.reject_time;
        [alert showInView:weakself.view];
    };
    return cell;
}

- (void)requestForYiJianZhuangChe:(NSString *)dp_id {
    [HttpRequest PostWithApi:LogisticsSupplierTaskZhuangChe params:@{@"sta_id":self.model.Id,@"type":@(2),@"dp_id":dp_id} progress:^(NSProgress * _Nonnull progress) {

    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            [self requestForDetail];
            [[NSNotificationCenter defaultCenter] postNotificationName:ReceiptDeliveryRefreshTaskManagerList object:nil];
            [MBProgressHUD leShowSuccessHUDAddedTo:self.view message:@"装车成功"];
        }
    } fail:^(NSError * _Nonnull error) {

    }];
}

- (void)requestForDaoDaWithTaskID:(NSString *)sta_id withDP_ID:(NSString *)dp_id withD_Status:(int)d_status {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:sta_id forKey:@"sta_id"];
    [dic setObject:dp_id forKey:@"dp_id"];
    if (d_status == 2) {
        //提货出发
        [dic setObject:@(1) forKey:@"type"];
    }else if (d_status == 7) {
        //送货出发
        [dic setObject:@(2) forKey:@"type"];
    }
    [dic setObject:@([[LJLocationManager shareManager] getCurrentLocation].latitude) forKey:@"lat"];
    [dic setObject:@([[LJLocationManager shareManager] getCurrentLocation].longitude) forKey:@"lng"];
    [HttpRequest PostWithApi:LogisticsSupplierTaskDaoDa params:dic progress:^(NSProgress * _Nonnull progress) {
            
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            [[NSNotificationCenter defaultCenter] postNotificationName:ReceiptDeliveryRefreshTaskManagerList object:nil];
            [self requestForDetail];
            [MBProgressHUD leShowSuccessHUDAddedTo:self.view message:@"已到达"];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    TaskManagerDetailCell *cell = [TaskManagerDetailCell TaskManagerDetailCellWithTableView:tableView];
    TaskManagerDetailOrderModel *model = self.model.list[indexPath.row];
    cell.model = model;
    return cell.height;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 40)];
    view.backgroundColor = Color_backgroundColor;
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(15, 11, ScreenW - 30, 19)];
    lab.text = @"任务明细";
    lab.font = BoldFontOfSize(18);
    lab.textColor = HexColor(0x2B2C44);
    [view addSubview:lab];
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 10)];
    view.backgroundColor = Color_backgroundColor;
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}

-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self stopTimer];
}

@end
